package com.imooc.service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.imooc.dao.MiaoshaUserDao;
import com.imooc.domain.MiaoshaUser;
import com.imooc.exception.GlobalException;
import com.imooc.redis.MiaoshaUserKey;
import com.imooc.redis.RedisService;
import com.imooc.result.CodeMsg;
import com.imooc.utils.MD5Util;
import com.imooc.utils.UUIDUtil;
import com.imooc.vo.LoginVo;

@Service
public class MiaoshaUserService {
	
	@Autowired
	private MiaoshaUserDao userDao;
	
	@Autowired
	private RedisService redisService;
	
	public static final String COOKIE_NAME_TOKEN = "token";
	
	public MiaoshaUser getById(long id){
		return userDao.getById(id);
	}
	
	public MiaoshaUser getByToken(HttpServletResponse response, String token) {
		if(StringUtils.isEmpty(token)){
			return null;
		}
		MiaoshaUser user = redisService.get(MiaoshaUserKey.TOKEN, token, MiaoshaUser.class);
		// 延长有效期
		if(user != null){
			addCookie(response, token, user);
		}
		return user;
	}

	public CodeMsg login(HttpServletResponse response, LoginVo vo) {
		if(vo == null){
			throw new GlobalException(CodeMsg.SERVER_ERROR);
		}
		String mobile = vo.getMobile();
		String formPass = vo.getPassword();
		//判断手机号是否存在
		MiaoshaUser user = getById(Long.parseLong(mobile));
		if(user == null){
			throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
		}
		String dbPass = user.getPassword();
		String salt = user.getSalt();
		
		String calcPass = MD5Util.formPassToDBPass(formPass, salt);
		System.out.println("calcPass="+calcPass);
		System.out.println("dbPass="+dbPass);
		if(!calcPass.equals(dbPass)){
			throw new GlobalException(CodeMsg.PASSWORD_ERROR);
		}
		// 生成Cookie
		String token = UUIDUtil.uuid();
		addCookie(response, token, user);
		
		return CodeMsg.SUCCESS;
		
	}

	private void addCookie(HttpServletResponse response, String token, MiaoshaUser user) {
		redisService.set(MiaoshaUserKey.TOKEN, token, user);
		Cookie cookie = new Cookie(COOKIE_NAME_TOKEN, token);
		cookie.setMaxAge(MiaoshaUserKey.TOKEN.expireSeconds());
		cookie.setPath("/");
		
		response.addCookie(cookie);
	}

	
}
